package com.itheima.service.impl;

import com.itheima.common.utils.DateUtils;
import com.itheima.dao.MemberDao;
import com.itheima.dao.OrderDao;
import com.itheima.dao.SetmealDao;
import com.itheima.dao.UserDao;
import com.itheima.pojo.BusinessReportVO;
import com.itheima.pojo.Order;
import com.itheima.pojo.SetmealHotVO;
import com.itheima.pojo.SetmealReportVO;
import com.itheima.service.ReportService;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class ReportServiceImpl implements ReportService {

    @Autowired
    private UserDao userDao;
    @Autowired
    private SetmealDao setmealDao;
    @Autowired
    private MemberDao memberDao;
    @Autowired
    private OrderDao orderDao;

    /**
     * 前30天内的会员数量统计
     * @return
     */
    public Map getMemberReport() {
        Map map = new HashMap();
        List months = new ArrayList<>();
        List memberCounts = new ArrayList<>();

        LocalDate dateBegin = LocalDate.now().minusDays(30);

        for (int i = 0; i < 30; i++) {
            LocalDate date = dateBegin.plusDays(i);
            Integer count = userDao.getDateSum(date);
            months.add(date);//每天
            memberCounts.add(count);//每天的数量
        }
        map.put("months", months);
        map.put("memberCount", memberCounts);
        return map;
    }

    /**
     * 前30天内的套餐预约占比
     * @return
     */
    public Map getSetmealReport() {
        LocalDate dateBegin = LocalDate.now().minusDays(30);
        LocalDate dateEnd = LocalDate.now().minusDays(1);

        List<SetmealReportVO> setmealReportVOList = setmealDao.getSetmealReport(dateBegin, dateEnd);
        List nameList = new ArrayList();
        for (SetmealReportVO setmealReportVO : setmealReportVOList) {
            nameList.add(setmealReportVO.getName());
        }

        Map map = new HashMap();
        map.put("setmealNames", nameList);
        map.put("setmealCount", setmealReportVOList);
        return map;
    }

    /**
     * 运营数据统计
     */
    public BusinessReportVO getBusinessReportData() {
        BusinessReportVO businessReportVO = new BusinessReportVO();

        //会员数据统计
        Integer totalMember = memberDao.getBeforeMonthDate(null);
        LocalDate dateBegin = LocalDate.now().minusDays(30);

        businessReportVO.setReportDate(dateBegin + "-" + LocalDate.now());

        // 获取30天前的数据
        Integer todayNewMember = memberDao.getBeforeMonthDate(dateBegin);
        try {
            //本周一
            String monday = DateUtils.parseDate2String(DateUtils.getThisWeekMonday());
            LocalDate dateTime = LocalDate.parse(monday, DateTimeFormatter.ofPattern("yyyy-MM-dd"));
            Integer thisWeekNewMember = memberDao.getBeforeMonthDate(dateTime);
            //本月一日
            String startDay = DateUtils.parseDate2String(DateUtils.getFirstDay4ThisMonth());
            dateTime = LocalDate.parse(startDay, DateTimeFormatter.ofPattern("yyyy-MM-dd"));
            Integer thisMonthNewMember = memberDao.getBeforeMonthDate(dateTime);

            //预约到诊数据统计
            String today = DateUtils.parseDate2String(DateUtils.getToday(), "yyyy-MM-dd");
            //今日预约数
            Integer todayOrderNumber = orderDao.getOrderDateInStatus(today, null);
            //今日到诊数
            Integer todayVisitsNumber = orderDao.getOrderDateInStatus(today, Order.ORDERSTATUS_YES);
            //本周预约数
            Integer thisWeekOrderNumber = orderDao.getOrderDateInStatus(monday, null);
            //本周到诊数
            Integer thisWeekVisitsNumber = orderDao.getOrderDateInStatus(monday, Order.ORDERSTATUS_YES);
            //本月预约数
            Integer thisMonthOrderNumber = orderDao.getOrderDateInStatus(startDay, null);
            //本月到诊数
            Integer thisMonthVisitsNumber = orderDao.getOrderDateInStatus(startDay, Order.ORDERSTATUS_YES);

            //热门套餐，获取30天内排名前3的套餐数据
            List<SetmealHotVO> hotSetmeal = setmealDao.getHotSetmeal(dateBegin);

            businessReportVO.setTodayNewMember(todayNewMember);
            businessReportVO.setTotalMember(totalMember);
            businessReportVO.setThisWeekNewMember(thisWeekNewMember);
            businessReportVO.setThisMonthNewMember(thisMonthNewMember);

            businessReportVO.setTodayOrderNumber(todayOrderNumber);
            businessReportVO.setTodayVisitsNumber(todayVisitsNumber);
            businessReportVO.setThisWeekOrderNumber(thisWeekOrderNumber);
            businessReportVO.setThisWeekVisitsNumber(thisWeekVisitsNumber);
            businessReportVO.setThisMonthOrderNumber(thisMonthOrderNumber);
            businessReportVO.setThisMonthVisitsNumber(thisMonthVisitsNumber);
            businessReportVO.setHotSetmeal(hotSetmeal);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return businessReportVO;
    }

    /**
     * 导出excel
     * @param response
     */
    public void exportBusinessReport(HttpServletResponse response) {
        // 设置响应的类型
        response.setContentType("application/vnd.ms-excel");
        response.setHeader("Content-Disposition", "attachment; filename=\"example.xlsx\"");

        //查询概览数据
        BusinessReportVO businessReportData = getBusinessReportData();
        //2. 通过POI将数据写入到Excel文件中
        String path = this.getClass().getClassLoader().getResource("").getPath() + "\\templates\\report_template.xlsx";
        try {
            InputStream in = new BufferedInputStream(new FileInputStream(path));
            //基于模板文件创建一个新的Excel文件
            XSSFWorkbook excel = new XSSFWorkbook(in);
            //获取表格文件的Sheet页
            XSSFSheet sheet = excel.getSheet("Sheet1");
            //填充数据--时间
            sheet.getRow(2).getCell(5).setCellValue("时间：" + businessReportData.getReportDate());
            //获得第5行
            XSSFRow row = sheet.getRow(4);
            row.getCell(5).setCellValue(businessReportData.getTodayNewMember());
            row.getCell(7).setCellValue(businessReportData.getTotalMember());

            //获得第6行
            row = sheet.getRow(5);
            row.getCell(5).setCellValue(businessReportData.getThisWeekNewMember());
            row.getCell(7).setCellValue(businessReportData.getThisMonthNewMember());

            //获得第8行
            row = sheet.getRow(7);
            row.getCell(5).setCellValue(businessReportData.getTodayOrderNumber());
            row.getCell(7).setCellValue(businessReportData.getTodayVisitsNumber());
            //获得第9行
            row = sheet.getRow(8);
            row.getCell(5).setCellValue(businessReportData.getThisWeekOrderNumber());
            row.getCell(7).setCellValue(businessReportData.getThisWeekVisitsNumber());
            //获得第10行
            row = sheet.getRow(9);
            row.getCell(5).setCellValue(businessReportData.getThisMonthOrderNumber());
            row.getCell(7).setCellValue(businessReportData.getThisMonthVisitsNumber());

            for (int i = 0; i < businessReportData.getHotSetmeal().size(); i++) {
                //获得第13行
                row = sheet.getRow(12 + i);
                row.getCell(4).setCellValue(businessReportData.getHotSetmeal().get(i).getName());
                row.getCell(5).setCellValue(businessReportData.getHotSetmeal().get(i).getSetmealCount());
                row.getCell(6).setCellValue(businessReportData.getHotSetmeal().get(i).getProportion());
            }

            //3. 通过输出流将Excel文件下载到客户端浏览器
            ServletOutputStream out = response.getOutputStream();
            excel.write(out);

            //关闭资源
            out.close();
            excel.close();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 导出PDF
     * @param response
     */
    public void exportBusinessReport4PDF(HttpServletResponse response) {
        // TODO 目前不需要导出PDF功能
    }

}
